﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Core.Exceptions.Database;
using System.Data.SqlClient;
using BSCMFF.Core.BusinessLayer;

namespace BSCMFF.Web.Pages.Surveys.Personalist
{
    /// <summary>
    /// Manage surveys.
    /// </summary>
    /// <remarks></remarks>
    public partial class ManageSurveys : BSCMFF.Core.MultiLanguagePage
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void Page_Load(object sender, EventArgs e)
        {
            RadGridSurveys.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;
        }

        /// <summary>
        /// Handles the ItemCommand event of the RadGridSurveys control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Web.UI.GridCommandEventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadGridSurveys_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "InitInsert")
            {
                Response.Redirect("CreateSurvey.aspx");
            }

            if (e.CommandName == "Preview")
            {
                GridEditableItem editedItem = e.Item as GridEditableItem;
                int sfID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);
                Response.Redirect("../FillSurvey.aspx?Preview=yes&Survey_FormID=" + sfID);
            }

            if (e.CommandName == "Start")
            {
                GridEditableItem editedItem = e.Item as GridEditableItem;
                BSCEntities context = new BSCEntities();
                int sfID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);

                Survey_Form sf = (from sfs in context.Survey_Form
                                  where sfs.ID == sfID
                                  select sfs).SingleOrDefault();

                sf.Started = true;
                AssignRandomEmployees(sf.ID, (int)sf.NumberOfEmployees);

                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new InconsistentDatabaseException("Couldn't start survey: " + ex.Message);
                }
                RadGridSurveys.Rebind();

            }
            if (e.CommandName == "Finish")
            {
                GridEditableItem editedItem = e.Item as GridEditableItem;
                BSCEntities context = new BSCEntities();
                int sfID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);

                Survey_Form sf = (from sfs in context.Survey_Form
                                  where sfs.ID == sfID
                                  select sfs).SingleOrDefault();

                sf.Started = true;
                sf.Finished = true;
                
                try
                {
                    context.SaveChanges();
                    context.FinishSurvey(sfID);
                }
                catch (Exception ex)
                {
                    throw new InconsistentDatabaseException("Couldn't finish survey: " + ex.Message);
                }
                RadGridSurveys.Rebind();
            }

            if (e.CommandName == "Delete")
            {
                GridEditableItem editedItem = e.Item as GridEditableItem;
                BSCEntities context = new BSCEntities();
                int sfID = Convert.ToInt32(editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["ID"]);

                Survey_Form sf = (from sfs in context.Survey_Form
                                  where sfs.ID == sfID
                                  select sfs).SingleOrDefault();

                context.DeleteObject(sf);

                try
                {
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new InconsistentDatabaseException("Couldn't delete survey: " + ex.Message);
                }
                RadGridSurveys.Rebind();
            }
        }

        /// <summary>
        /// Assigns the random employees.
        /// </summary>
        /// <param name="surveyID">The survey ID.</param>
        /// <param name="numberOfEmployees">The number of employees.</param>
        /// <remarks></remarks>
        private void AssignRandomEmployees(int surveyID, int numberOfEmployees)
        {
            BSCEntities context = new BSCEntities();

            List<int> usersID = (from user in context.Users
                                 select user.ID).ToList();

            if (numberOfEmployees > usersID.Count)
            {
                numberOfEmployees = usersID.Count;
            }

            List<int> randomizedUsersIDs = ShuffleList<int>(usersID);

            
            for (int i = 0; i < numberOfEmployees; ++i)
            {
                Survey_User su = new Survey_User();
                su.Survey_Form_FK = surveyID;
                su.User_FK = randomizedUsersIDs[i];
                su.Filled = false;
                context.AddToSurvey_User(su);
            }

            try
            {
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new InconsistentDatabaseException("Couldn't assign survey to employees: " + ex.Message);
            }
        }

        /// <summary>
        /// Shuffles the list.
        /// </summary>
        /// <typeparam name="E"></typeparam>
        /// <param name="inputList">The input list.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        private List<E> ShuffleList<E>(List<E> inputList)
        {
            List<E> randomList = new List<E>();

            Random r = new Random();
            int randomIndex = 0;
            while (inputList.Count > 0)
            {
                randomIndex = r.Next(0, inputList.Count); //Choose a random object in the list
                randomList.Add(inputList[randomIndex]); //add it to the new, random list
                inputList.RemoveAt(randomIndex); //remove to avoid duplicates
            }

            return randomList; //return the new random list
        }

        /// <summary>
        /// Handles the ItemDataBound event of the RadGridSurveys control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Web.UI.GridItemEventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadGridSurveys_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem item = (GridDataItem)e.Item;
                int userID = Int32.Parse(item.OwnerTableView.DataKeyValues[item.ItemIndex]["ID"].ToString());
                int currentUserID = (int)Session["loggedUserID"];

                bool started = ((CheckBox)item["Started"].Controls[0]).Checked;
                bool finished = ((CheckBox)item["Finished"].Controls[0]).Checked;

                if (started || finished)
                {
                    item["StartCommand"].Controls[0].Visible = false;
                }
                if (finished)
                {
                    item["FinishCommand"].Controls[0].Visible = false;
                }
            } 
        }
    }
}